#include "Picture.h"
#include "../../draw/TextureManager.h"
#include "Frame.h"

Picture::Picture(const char* textureFile, float uMin, float uMax, float vMin, float vMax)
: Object()
, uMin(uMin)
, uMax(uMax)
, vMin(vMin)
, vMax(vMax)
, textureIndex(-1) {
	//If we get a texture file, try and load it
	if(strlen(textureFile) != 0)
		textureIndex = TextureManager::Instance().getTexture(textureFile);
}

void Picture::onLeftClick() {
}
void Picture::onKeyPress() {
}
void Picture::onRollOver() {
}

void Picture::getDimensions(double* width, double* height) {
	if(width != NULL) {
		*width = dimensions.x + 2*padding;
	}
	if(height != NULL) {
		*height = dimensions.y + 2*padding;
	}
}

void Picture::draw(unsigned long) {
	glEnable(GL_TEXTURE_2D);
	glColor4d(color.r,color.g,color.b,color.a);
	
	//Bind the texture to use
	if(textureIndex != unsigned(-1))
		glBindTexture(GL_TEXTURE_2D, textureIndex);
	glBegin(GL_QUADS);
		glTexCoord2f(uMin, vMin);	glVertex3f(drawPos.x,drawPos.y, drawPos.z);
		glTexCoord2f(uMax, vMin);	glVertex3f(drawPos.x + dimensions.x,drawPos.y, drawPos.z);
		glTexCoord2f(uMax, vMax);	glVertex3f(drawPos.x + dimensions.x,drawPos.y + dimensions.y, drawPos.z);
		glTexCoord2f(uMin, vMax);	glVertex3f(drawPos.x, drawPos.y + dimensions.y, drawPos.z);
	glEnd();
	glDisable(GL_TEXTURE_2D);
	//This ensures that texturing doesn't mess with anything else
}

void Picture::onRealign(float minX, float maxX, float minY, float maxY) {
	switch(horizAlignment) {
	case LEFT:
		drawPos.x = padding;
		break;
	case RIGHT:
		drawPos.x = maxX - dimensions.x - padding;
		break;
	case HORIZ_MIDDLE:
		drawPos.x = (maxX + minX - dimensions.x) / 2.0;
		break;
	case ABSOLUTE:
	default:
		break;
	}
	switch(vertAlignment) {
	case TOP:
		drawPos.y = maxY - dimensions.y - padding;
		break;
	case BOTTOM:
		drawPos.y = padding;
		break;
	case VERT_MIDDLE:
		drawPos.y = (maxY + minY - dimensions.y) / 2.0;
		break;
	case ABSOLUTE:
	default:
		break;
	}
}

void Picture::loadFromXML(ticpp::Node* node, int Z, Frame* f) {
	using namespace ticpp;
	Object::loadFromXML(node,Z, f);
	
	Element* elem = node->ToElement();
	elem->GetAttribute("uMin", &uMin, false);
	elem->GetAttribute("uMax", &uMax, false);
	elem->GetAttribute("vMin", &vMin, false);
	elem->GetAttribute("vMax", &vMax, false);
	std::string val;
	elem->GetAttribute("texture", &val, false);
	if(val.length() != 0)	//If we get a texture, load it
		textureIndex = TextureManager::Instance().getTexture(val.c_str());
		
	Frame::parseChild(node, Z-1, f);
	
}

